package com.lzkjiot.service.gnss.transger.core.transfer.condition;

import com.alibaba.fastjson.JSON;
import com.lzkjiot.service.gnss.transger.core.config.BaseStations;
import com.lzkjiot.service.gnss.utils.TbGatewayMqttClient;
import com.lzkjiot.service.gnss.utils.TbRestClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.thingsboard.server.common.data.Device;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class GnssConditionTransferWorker{

    @Value("${tb.gateway.restapi.url}")
    private String restApiUrl;

    @Value("${tb.gateway.restapi.username}")
    private String restApiUsername;

    @Value("${tb.gateway.restapi.password}")
    private String restApiPassword;

    @Autowired
    BaseStations baseStations;

    TbRestClient tbRestClient;

    @Autowired
    TbGatewayMqttClient tbGatewayMqttClient;

    private final ExecutorService execWorkerPool = Executors.newFixedThreadPool(2);

    @PostConstruct
    private void init(){
        log.info("=== init tbMqttClient ===");
        if(tbRestClient == null){
            tbRestClient = new TbRestClient(new RestTemplate(), restApiUrl);
            tbRestClient.login(restApiUsername, restApiPassword);
        }
    }
    public void send(String deviceId, String data) {
        String deviceName = "";
        if(baseStations.getStations().contains(deviceId)){
            deviceName = "B" + deviceId;
        } else {
            deviceName = "R" + deviceId;
        }
        execWorkerPool.execute(new GnssConditionWorker(deviceName, data, tbRestClient, tbGatewayMqttClient));
    }

}

class GnssConditionWorker implements Runnable{
    String deviceName = "";
    String data= "";
    TbRestClient tbRestClient;
    TbGatewayMqttClient tbGatewayMqttClient;
    GnssConditionWorker(String deviceName, String data, TbRestClient tbRestClient,
                        TbGatewayMqttClient tbGatewayMqttClient){
        this.deviceName = deviceName;
        this.data = data;
        this.tbRestClient = tbRestClient;
        this.tbGatewayMqttClient = tbGatewayMqttClient;
    }
    @Override
    public void run() {
        try{
            String deviceType = "GNSS-N1";
            if (deviceName.startsWith("B")){
                deviceType = "GNSS基准点";
            }
            Device device = findDeviceByName(deviceName, deviceType);
            Map<String, Object> mapData = new HashMap<>();
            mapData.put("gnssConditionData", JSON.parse(data));
            mapData.put("scope", "share");
            mapData.put("ts", System.currentTimeMillis());
            tbGatewayMqttClient.publishAttributes(deviceName, mapData);
            System.out.println("[ConditionTransWorker] To device "+ deviceName + " data:" + mapData);
        } catch (Exception ex){
            System.err.println("[ConditionTransWorker] To device "+ deviceName + " exception:" + ex.getMessage());
        }

    }

    private Device findDeviceByName(String deviceName, String deviceType){
        Device device = null;
        Optional<Device> optionalDevice = tbRestClient.getTenantDevice(deviceName);
        if(optionalDevice.isPresent()){
            device = optionalDevice.get();
        } else {
            device = tbRestClient.createDevice(deviceName, deviceType);
        }
        return device;
    }
}
